﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using Tesla.Util.UIUtilities;

namespace Tesla.Web.Controls
{
    public partial class TimeSheetGridView : System.Web.UI.UserControl
    {
        private DataSet _gridData;

        protected void Page_Load(object sender, EventArgs e)
        {
        }


        public DataSet SourceData
        {
            //TODO: Proper dataset should be prepared before return
            get { return this.gvTimeSheet.DataSource as DataSet; }
            set
            {
                if (value != null && ((DataSet)value).Tables.Count == 2)
                {
                    _gridData = value;
                    this.ParseSourceData();

                }
            }
        }
        private void ParseSourceData()
        {
            string headerText = string.Empty;
            string[] dateIds = new string[7];
            int i = 0;
            DataTable dtProj = _gridData.Tables[0];
            DataTable dtWeek = _gridData.Tables[1];

            foreach (DataRow r in dtWeek.Rows)
            {
                DataColumn dc = new DataColumn();
                dc.ColumnName = r["calendardate"].ToString();
                dtProj.Columns.Add(dc);
                dateIds[i] = r["calendardaysid"].ToString();
                i++;
            }
            gvTimeSheet.DataSource = dtProj;

            for (int col = 7; col > 0; col--)
            {
                headerText = dtProj.Columns[dtProj.Columns.Count - col].ColumnName;
                string textBoxId = string.Format("txt_{0}", dateIds[7 - col]);
                this.AddTextBoxColumn(headerText, headerText, textBoxId);
            }

            gvTimeSheet.DataBind();
        }

        private void AddTextBoxColumn(string headerText, string dataField, string id)
        {
            TemplateField tf = new TemplateField();
            tf.HeaderText = headerText;
            tf.ItemTemplate = new TemplateFieldColumn<TextBox>(dataField, id);
            gvTimeSheet.Columns.Add(tf);
        }
    }
}